let logger = require("pomelo-logger").getLogger(__filename);
let mailDataCreator = require("../entities/mailData").create;
let mailDataLoader = require("../entities/mailData").loadFromBSON;
let DateUtil = require("../../utils/dateUtil");

let MailDataService = function (app) {
    this.app = app;
    this.mailDatas = new Map();
    this.nextMailId = 1000;
};

MailDataService.prototype.initialize = function () {
    let mailDataDao = this.app.get("mailDataDao");
    let self = this;
    let maxMailId = 1000;
    mailDataDao.load(DateUtil.nowMS() - 7 * 24 * 3600 * 1000, function (documents) {
        documents = documents || [];
        for(let document of documents) {
            self.mailDatas.set(document["id"], mailDataLoader(document));
        }
    });
    mailDataDao.getNextMailId(function (id) {
        if(!!id) {
            maxMailId = id;
        }
        self.nextMailId = maxMailId + 1;
        console.log("MailDataService initialize nextMailId=" + self.nextMailId);
    });
};

MailDataService.prototype.addMailData = function (title, mailType, content, award, sender, receiverUids, callback) {
    let mailId = this.nextMailId;
    this.nextMailId = this.nextMailId + 1;
    let mailData = mailDataCreator(mailId, title, mailType, content, award, sender, receiverUids);
    let mailDataDao = this.app.get("mailDataDao");
    this.mailDatas.set(mailData.getId(), mailData);
    mailDataDao.insert(mailData.toBSON(), function (dbId) {
        if (!!dbId) {
            mailData.setDBId(dbId);
            callback(mailData);
        } else {
            logger.error("insert maiData error. mailData is " + JSON.stringify(mailData.toBSON()));
            callback(null);
        }
    });
};

MailDataService.prototype.getUnReceivedMailDatas = function (uid, ts) {
    let result = [];
    for (let mailData of this.mailDatas.values()) {
        if (mailData.getSenderTime() > ts && mailData.isReceiver(uid)) {
            result.push(mailData);
        }
    }
    return result;
};

MailDataService.prototype.findById = function (id) {
    if (this.mailDatas.has(id)) {
        return this.mailDatas.get(id);
    }
    return null;
};

exports.create = function (app) {
    return new MailDataService(app);
};